package com.spzx.order.controller;

import java.util.List;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spzx.common.core.domain.R;
import com.spzx.common.security.annotation.InnerAuth;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.dto.OrderSubmitDTO;
import com.spzx.order.service.IOrderItemService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.spzx.common.log.annotation.Log;
import com.spzx.common.log.enums.BusinessType;
import com.spzx.common.security.annotation.RequiresPermissions;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.utils.poi.ExcelUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.spzx.common.core.web.page.TableDataInfo;

/**
 * 订单Controller
 *
 * @author atguigu
 * @date 2024-10-29
 */
@Tag(name = "订单接口管理")
@RestController
@RequestMapping("/orderInfo")
public class OrderInfoController extends BaseController
{
    @Resource
    private IOrderInfoService orderInfoService;
    @Resource
    private IOrderItemService orderItemService;
    @InnerAuth
    @Operation(summary = "内部调用接口：根据订单号查询订单详情")
    @GetMapping("/getPaymentInfo/{orderNo}")
    public R<OrderInfo> getPaymentInfo(@PathVariable("orderNo")String orderNo
    ){
        return R.ok(orderInfoService.getOne(Wrappers.lambdaQuery(OrderInfo.class)
                .eq(OrderInfo::getOrderNo,orderNo)));
    }

    @Operation(summary = "查询订单详情")
    @GetMapping("/getOrderInfo/{orderId}")
    public AjaxResult getOrderInfo(@PathVariable("orderId")Long orderId
    ){
        return success(orderInfoService.getById(orderId));
    }

    @Operation(summary = "用户取消订单")
    @RequestMapping("/cancelOrder/{orderId}")
    public AjaxResult cancelOrder(@PathVariable("orderId")Long orderId){
        return toAjax(orderInfoService.cancelOrder(orderId));
    }


    /*userOrderInfoList/1/10?orderStatus=*/
    @Operation(summary = "查询用户的指定状态的订单分页数据")
    @GetMapping("/userOrderInfoList/{pageNum}/{pageSize}")
    public TableDataInfo userOrderInfoList(@PathVariable("pageNum") Integer pageNum,
                                           @PathVariable("pageSize") Integer pageSize,
                                           Integer orderStatus){
        Page<OrderInfo> page = orderInfoService.page(new Page<OrderInfo>(pageNum, pageSize), Wrappers.lambdaQuery(OrderInfo.class)
                //参数1,是否使用当前条件
                .eq(orderStatus != null, OrderInfo::getOrderStatus, orderStatus)
                .eq(OrderInfo::getUserId, SecurityUtils.getUserId())
                .orderByDesc(OrderInfo::getCreateTime)//按照创建时间降序排列
        );
        //前端需要查询订单和它的所有订单项集合
        page.getRecords().forEach(orderInfo -> {
             List<OrderItem> orderItems = orderItemService.list(Wrappers.lambdaQuery(OrderItem.class)
                    .eq(OrderItem::getOrderId, orderInfo.getId()));
             orderInfo.setOrderItemList(orderItems);
        });
        //orderItemList
        return getDataTable(page);
    }

    /*
        新的业务模块实现,:
            1.创建接口,保证可以接受到请求
            2.研究如何接收请求参数
            3.业务逻辑实现
            4.返回结果
    * */



    /*
     elementplus的组件：
     springcloud的常用组件：
     rabbitmq的五种消息模型：
     rabbitmq的消息可靠性：
         -
     线程池七大参数
     线程池底层工作原理
     ReentrantLock原理：AQS+CAS
     线程安全的集合类：
         Hashtable：  同步方法
         ConcurrentHashMap  局部锁+CAS保证线程安全  重点！！！
         SynchronizedMap： Collections  同步代码块+装饰者模式







     接口设计：
         1、要能够正确接收前端的请求和参数
             - 如果前端的参数后端没有javabean接收 可以自定义DTO类接收
         2、业务
         3、按照前端(接口文档)要求返回数据
             - 如果接口文档或前端页面 要求的响应数据 后端没有javabean可以组装，可以自定义VO类组装数据

  */
    @PostMapping("/submitOrder")
    @Operation(summary = "提交订单接口")
    public AjaxResult submitOrder(@RequestBody OrderSubmitDTO orderSubmitDTO){
        Long orderId =  orderInfoService.submitOrder(orderSubmitDTO);
        return success(orderId);
    }


    @GetMapping("/trade")
    @Operation(summary = "结算页查询结算购物项列表")
    public AjaxResult trade(){
        return success(orderInfoService.trade());
    }

    /**
     * 查询订单列表
     */
    @Operation(summary = "查询订单列表")
    @RequiresPermissions("order:orderInfo:list")
    @GetMapping("/list")
    public TableDataInfo list(OrderInfo orderInfo)
    {
        startPage();
        List<OrderInfo> list = orderInfoService.selectOrderInfoList(orderInfo);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @Operation(summary = "导出订单列表")
    @RequiresPermissions("order:orderInfo:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderInfo orderInfo)
    {
        List<OrderInfo> list = orderInfoService.selectOrderInfoList(orderInfo);
        ExcelUtil<OrderInfo> util = new ExcelUtil<OrderInfo>(OrderInfo.class);
        util.exportExcel(response, list, "订单数据");
    }

    /**
     * 获取订单详细信息
     */
    @Operation(summary = "获取订单详细信息")
    @RequiresPermissions("order:orderInfo:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(orderInfoService.getById(id));
    }

    /**
     * 新增订单
     */
    @Operation(summary = "新增订单")
    @RequiresPermissions("order:orderInfo:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OrderInfo orderInfo)
    {
        return toAjax(orderInfoService.save(orderInfo));
    }

    /**
     * 修改订单
     */
    @Operation(summary = "修改订单")
    @RequiresPermissions("order:orderInfo:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OrderInfo orderInfo)
    {
        return toAjax(orderInfoService.updateById(orderInfo));
    }

    /**
     * 删除订单
     */
    @Operation(summary = "删除订单")
    @RequiresPermissions("order:orderInfo:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(orderInfoService.removeBatchByIds(Arrays.asList(ids)));
    }
}
